package com.example.demo.common.util;

import cn.hutool.core.codec.Base64;
import com.example.demo.smartLamp.entity.User;
import com.example.demo.smartLamp.service.IUserService;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.codec.Hex;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class JwtUitls {
    @Autowired
    private static IUserService userService;
    /**
     * 过期时间500分钟
     */
    //private static final long EXPIRE_TIME=500*60*1000;
    /**
     * 加密密钥
     */
    private static final String KEY = "qirongbohushaoyu";
    private static final String KEY_CLAIMS = "key_claims";
    private static final String SUBJECT = "key_subject";




    /**
     * 生成token
     * @param id    用户id
     * @param userName  用户名
     * @return token
     */
    public static String createToken(String id, String userName){
//        Map<String,Object> header = new HashMap();
//        header.put("typ","JWT");
//        header.put("alg","HS256");
//        //setID:用户ID        //setExpiration:token过期时间  当前时间+有效时间
//        //setSubject:用户名
//        //setIssuedAt:token创建时间
//        //signWith:加密方式
//        JwtBuilder builder = Jwts.builder().setHeader(header)
//                .setId(id)
//                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME))
//                .setSubject(userName)
//                .setIssuedAt(new Date())
//                .signWith(SignatureAlgorithm.HS256, KEY);
//        return builder.compact();
        //Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

        String key = "0123456789_0123456789_0123456789";
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), SignatureAlgorithm.HS256.getJcaName());

        Date now = new Date();
        //增加2分钟的过期时间，用于测试
        Date expirationDate = DateUtils.addMinutes(now, 240);

        Map<String, Object> claims = new HashMap<String, Object>();
        User user = new User();
        user.setUserId(id);
        user.setUserName(userName);
        claims.put(KEY_CLAIMS, user);

        String token = Jwts.builder()
                .setClaims(claims)
                .setId(id)
                .setSubject(SUBJECT)
                .setIssuedAt(now)
                .setExpiration(expirationDate)
                .signWith(secretKey)
                .compact();
        return token;

    }

    /**
     * 验证token是否有效
     * @param token  请求头中携带的token
     * @return  token验证结果  2-token过期；1-token认证通过；0-token认证失败
     */
    public static int verify(String token){
        String key = "0123456789_0123456789_0123456789";
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), SignatureAlgorithm.HS256.getJcaName());
        Claims claims = null;
        try {
            //token过期后，会抛出ExpiredJwtException 异常，通过这个来判定token过期，
            claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token).getBody();
        }catch (ExpiredJwtException e){
            return 2;
        }
        //从token中获取用户id，查询该Id的用户是否存在，存在则token验证通过
//        String id = claims.getId();
//        User user = userService.selectUserById(id);
//        if(user != null){
//            return 1;
//        }else{
//            return 0;
//        }

        return 1;
    }
}
